package cn.labbook.bluetooth.controller;

import cn.labbook.bluetooth.common.MyPage;
import cn.labbook.bluetooth.common.ResultDto;
import cn.labbook.bluetooth.common.SmsTemplateEnum;
import cn.labbook.bluetooth.constant.AdminConstant;
import cn.labbook.bluetooth.constant.AmmeterConstant;
import cn.labbook.bluetooth.constant.UserConstant;
import cn.labbook.bluetooth.entity.*;
import cn.labbook.bluetooth.service.*;
import cn.labbook.bluetooth.util.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/wx")
@Slf4j
public class WXController extends AbstractController {

    @Autowired
    IUserService userService;
    @Autowired
    IAmmeterService ammeterService;
    @Autowired
    IAdminService adminService;
    @Autowired
    IWarnAmmeterService warnAmmeterService;
    @Autowired
    IWarnAmmeterViewService warnAmmeterViewService;
    @Autowired
    IPayViewService payViewService;
    @Autowired
    ITenantPayService tenantPayService;
    @Autowired
    IAdminResService adminResService;

    @RequestMapping("login")
    @ResponseBody
    public ResultDto wxLogin(String code, HttpServletRequest request) throws IOException {
        String appid = "wxafeeae8c758d838d";
        String secret = "f57255e85a65b3454fe3e00d81cf3d9b";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        URL getUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
        connection.connect();
        // 取得输入流，并使用Reader读取
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        // 断开连接
        connection.disconnect();
        Map<String, Object> map = JsonUtils.getMapFromJson(sb.toString());
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getOpenId, map.get("openid"));
        User user = userService.getOne(lambda);
        System.out.println(user);

        String id = request.getSession().getId();
        if (user == null) {
            user = new User();
            user.setUserId(GenerateIdUtils.get32Varchar());
            user.setOpenId((String) map.get("openid"));
            user.setCreateTime(new Date());
            user.setType(UserConstant.TENANT);
            userService.save(user);
        }
        user.setSessionId(id);
        log.info("=============================>"+user);
        return success(user);
    }

    @RequestMapping({"addLog"})
    @ResponseBody
    public ResultDto addLog(String ammeterId, String warnType) {
        System.out.println(ammeterId);
        WarnAmmeter warnAmmeter = new WarnAmmeter();
        warnAmmeter.setAmmeterId(ammeterId);
        warnAmmeter.setGmtCreate(new Date());
        warnAmmeter.setId(GenerateIdUtils.get32Varchar());
        warnAmmeter.setLocation(((Ammeter)this.ammeterService.getById(ammeterId)).getLocation());
        warnAmmeter.setWarnType(warnType);
        if (this.warnAmmeterService.save(warnAmmeter))
            return success("保存成功");
        return fail("保存异常");
    }

    @RequestMapping({"syncFail"})
    @ResponseBody
    public ResultDto syncFail(String ammeterId) {
        WarnAmmeter warnAmmeter = new WarnAmmeter();
        warnAmmeter.setAmmeterId(ammeterId);
        warnAmmeter.setGmtCreate(new Date());
        warnAmmeter.setId(GenerateIdUtils.get32Varchar());
        warnAmmeter.setLocation(this.ammeterService.getById(ammeterId).getLocation());
        warnAmmeter.setWarnType("充值后电表同步失败");
        this.warnAmmeterService.save(warnAmmeter);
        Ammeter ammeter = this.ammeterService.getById(ammeterId);
        User user = this.userService.getById(ammeter.getUserId());
        MessageUtil.sendFailMessage(user.getMobilephone(), "平台数据与电表同步时出错,请重新扫码同步电表数据", "SMS_173766101");
        return success();
    }

    @RequestMapping({"logins"})
    @ResponseBody
    public ResultDto wxLogins(String openid, HttpServletRequest request) throws IOException {
        log.info("进入测试登录方法");
        LambdaQueryWrapper<User> lambda = (new QueryWrapper()).lambda();
        lambda.eq(User::getOpenId, openid);
        User user = this.userService.getOne(lambda);
        System.out.println(user);
        String id = request.getSession().getId();
        if (user == null) {
            user = new User();
            user.setUserId(GenerateIdUtils.get32Varchar());
            user.setOpenId(openid);
            user.setCreateTime(new Date());
            user.setType(Integer.valueOf(0));
            this.userService.save(user);
        }
        user.setSessionId(id);
        log.info("登录成功"+ user.toString());
        log.info("=============================>" + user);
        return success(user);
    }

    //完善房客信息（姓名电话）
    @RequestMapping("complete")
    @ResponseBody
    public ResultDto complete(String userId,String userName,String mobilephone) {
        User user = userService.getById(userId);
        if(user==null){return fail();}
        user.setUserName(userName);
        user.setMobilephone(mobilephone);
        userService.updateById(user);
        return success(user);
    }

    //短信发送
    @RequestMapping("message")
    @ResponseBody
    public ResultDto message(String ammeterId,String type,String openId,HttpServletRequest request) {
        String managerId = ammeterService.getById(ammeterId).getManagerId();
        String mobilephone = adminService.getById(managerId).getMobilephone();
        String CODE = null;
        if(type.equals("0")){
            CODE = MessageUtil.sendShortMessage(mobilephone, SmsTemplateEnum.VERIFICATION_CODE.getCode());
        }else if(type.equals("1")){
            LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
            lambda.eq(User::getOpenId,openId);
            User one = userService.getOne(lambda);
            CODE = MessageUtil.sendBindingMessage(mobilephone, one.getMobilephone(), one.getUserName(), SmsTemplateEnum.BIND_AMMETER.getCode());
        }else if(type.equals("2")){
            Ammeter ammeter = ammeterService.getById(ammeterId);
            User user = userService.getById(ammeter.getUserId());
            CODE = MessageUtil.sendUntyingMessage(mobilephone, user.getUserName(),ammeter.getAmount(),ammeter.getBalance(), SmsTemplateEnum.REFUND_APPLICATION.getCode());

        }
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        session.setAttribute("code", CODE);
        System.out.println(session.getAttribute("code"));
        return success();
    }

    //成为房东
    @RequestMapping("become")
    @ResponseBody
    public ResultDto become(String userId, String adminId) {
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getAdminId, adminId);
        if (userService.getOne(lambda) != null) {
            return fail("该房东已经绑定微信");
        }
        if (userService.getById(userId).getAdminId() != null) {
            return fail("该微信已绑定房东");
        }
        User user = userService.getById(userId);
        user.setAdminId(adminId);
        user.setType(UserConstant.LANDLORD);
        return userService.updateById(user) ? success() : fail();
    }

    //(房客绑定电表）
    @RequestMapping("binding")
    @ResponseBody
    public ResultDto binding(String ammeterId, String userId, String code, HttpServletRequest request) {
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        System.out.println(session.getAttribute("code"));
        if (code.equals(String.valueOf(session.getAttribute("code")))) {
            Ammeter ammeter = new Ammeter();
            ammeter.setAmmeterId(ammeterId);
            ammeter.setBalance(0.00);
            ammeter.setUserId(userId);
            WarnAmmeter warnAmmeter = new WarnAmmeter();
            warnAmmeter.setAmmeterId(ammeterId);
            warnAmmeter.setGmtCreate(new Date());
            warnAmmeter.setId(GenerateIdUtils.get32Varchar());
            warnAmmeter.setLocation(ammeterService.getById(ammeterId).getLocation());
            warnAmmeter.setWarnType("房客入住");
            warnAmmeterService.save(warnAmmeter);
            return ammeterService.updateById(ammeter) ? success() : fail();
        } else {
            return fail("验证码不正确");
        }
    }

    //(房客退房）
    @RequestMapping("relieve")
    @ResponseBody
    public ResultDto relieve(String ammeterId, String userId, String code, HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        System.out.println(session.getAttribute("code"));
        if (code.equals(String.valueOf(session.getAttribute("code")))) {
            if (ammeterService.getById(ammeterId).getUserId().equals(userId)) {
                Ammeter ammeter = new Ammeter();
                ammeter.setAmmeterId(ammeterId);
                ammeter.setUserId("");
                ammeter.setBalance(0.00);
                WarnAmmeter warnAmmeter = new WarnAmmeter();
                warnAmmeter.setAmmeterId(ammeterId);
                warnAmmeter.setGmtCreate(new Date());
                warnAmmeter.setId(GenerateIdUtils.get32Varchar());
                warnAmmeter.setLocation(ammeterService.getById(ammeterId).getLocation());
                warnAmmeter.setWarnType("房客退房");
                warnAmmeter.setIsSynchrony(0);
                warnAmmeterService.save(warnAmmeter);

//                String key3 = session.getAttribute("key3").toString();
//                String key4 = session.getAttribute("key4").toString();
//                ResultDto resultDto = new ResultDto();
//                String s = "0000000000000000";
//                byte[] encrypt = algorithm.encrypt(algorithm.toByteArray(s), key3);
//                String s1 = "3236343A77665544"+algorithm.encryptResult(encrypt, key4);
//                Protocol645 build = Protocol645BuildUtils.build(ammeterId, (byte) 0x03, algorithm.toByteArray(s1));
//                byte[] bytes = Protocol645Utils.toBytes(build);
//                String s3 = algorithm.toString(bytes);
//                Map<String,String> map= new HashMap<>();
//                LambdaQueryWrapper<WarnAmmeter> lambda = new QueryWrapper<WarnAmmeter>().lambda();
//                lambda.eq(WarnAmmeter::getIsSynchrony,0);
//                lambda.eq(WarnAmmeter::getAmmeterId,ammeterId);
//                WarnAmmeter one = warnAmmeterService.getOne(lambda);
//                if(one == null){
//                    return success();
//                }
//                map.put("data","FEFEFEFE".concat(s3));
//                map.put("warn_ammeter_id",one.getId());
//                resultDto.setData(map);
//                resultDto.setCode(2);
//                return resultDto;
                return ammeterService.updateById(ammeter) ? success() : fail();
            } else {
                return fail("您未绑定该电表");
            }


        } else {
            return fail("验证码不正确");
        }
    }

    @RequestMapping({"adminRelieve"})
    @ResponseBody
    public ResultDto adminRelieve(String ammeterId, HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        Ammeter ammeter = new Ammeter();
        ammeter.setAmmeterId(ammeterId);
        ammeter.setUserId("");
        ammeter.setBalance(0.0D);
        WarnAmmeter warnAmmeter = new WarnAmmeter();
        warnAmmeter.setAmmeterId(ammeterId);
        warnAmmeter.setGmtCreate(new Date());
        warnAmmeter.setId(GenerateIdUtils.get32Varchar());
        warnAmmeter.setLocation(this.ammeterService.getById(ammeterId).getLocation());
        warnAmmeter.setWarnType("房东解绑房客（退房）");
        warnAmmeter.setIsSynchrony(0);
        this.warnAmmeterService.save(warnAmmeter);
        return this.ammeterService.updateById(ammeter) ? success() : fail();
    }

    @RequestMapping("payment")
    @ResponseBody
    public ResultDto payment(String ammeterId, String price, String userId) {
        //这里写支付方法
        Ammeter ammeter = ammeterService.getById(ammeterId);
        Double balance = ammeter.getBalance() + Double.parseDouble(price);
        ammeter.setBalance(balance);
        return ammeterService.updateById(ammeter) ? success() : fail();
    }

    @RequestMapping("blecheck")
    @ResponseBody
    public ResultDto blecheck() {
        return null;
    }

    @RequestMapping("getAmmeter")
    @ResponseBody
    public ResultDto getAmmeter(String ammeterId) {
        Ammeter ammeter = ammeterService.getById(ammeterId);
        if (ammeter != null) {
            return success(ammeter);
        }
        return fail();
    }

    @RequestMapping("getAmmeterList")
    @ResponseBody
    public ResultDto getAmmeterList(String userId, MyPage<Ammeter> page, String ammeterAddress) {
        log.info("userId========>"+userId);
        if (StringUtils.isBlank(userId)) {
            return fail();
        }
        User user = userService.getById(userId);
        log.info("user========>"+user.toString());
        LambdaQueryWrapper<Ammeter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Ammeter::getManagerId, user.getAdminId());
        wrapper.eq(Ammeter::getStatus, AmmeterConstant.ACTIVATE);
        if (StringUtils.isNotBlank(ammeterAddress)) {
            wrapper.like(Ammeter::getLocation, ammeterAddress);
        }
        ammeterService.page(page, wrapper).getRecords().forEach(ammeter -> {
            if (ammeter.getReadingTime()==null) {
                ammeter.setSex("2");
            }else{
            if (TimeUtils.getBetweenSeconds(new Date(), ammeter.getReadingTime()) < 60 * 60 * 24 * 60) {
                ammeter.setSex("1");
            } else {
                ammeter.setSex("0");
            }
        }
        });
        return success(page);
    }

    @RequestMapping("myAmmeter")
    @ResponseBody
    public ResultDto myAmmeter(String userId) {
        User user = userService.getById(userId);
        if (user.getType() == UserConstant.LANDLORD) {
            return success();
        } else {
            return fail("您不是房东，请联系管理员申请");
        }
    }

    @RequestMapping("activate")
    @ResponseBody
    public ResultDto activate(Ammeter ammeter)  {
        Ammeter a = ammeterService.getById(ammeter.getAmmeterId());
        if (a == null) {
            return fail("该电表不存在");
        }
        if (a.getStatus().equals(AmmeterConstant.ACTIVATE)) {
            return fail("电表已绑定");
        }
        ammeter.setActivateTime(new Date());
        ammeter.setStatus(AmmeterConstant.ACTIVATE);
        ammeter.setAmount(0.0);
        ammeter.setBalance(0.0);
        ammeter.setPayPrice(100.0);
        ammeter.setManagerId(userService.getById(ammeter.getUserId()).getAdminId());
        ammeter.setValve(AmmeterConstant.valve.OFF);
        ammeter.setServerStatus(AmmeterConstant.serverStatus.NOTEXPIRE);
        ammeter.setEffectTime(new Date());
        ammeter.setOweStatus(AmmeterConstant.oweStatus.YES);
        ammeter.setIsSkimp(AmmeterConstant.IsSkimp.YES);
        ammeter.setUserId(null);
        return ammeterService.updateById(ammeter) ? success() : fail();
    }

    @RequestMapping("keep")
    @ResponseBody
    public ResultDto keep(String ammeterId) {
        Ammeter ammeter1 = ammeterService.getById(ammeterId);
        if (ammeter1 == null) {
            return fail("该电表不存在，请扫描正确的二维码");
        }
        if (!userService.getById(ammeter1.getUserId()).getAdminId().equals(ammeter1.getManagerId())) {
            return fail("您没有绑定此电表");
        }
        if (ammeter1.getStatus().equals(AmmeterConstant.NOTACTIVATE)) {
            return fail("该电表未激活");
        }
        ammeter1.setStatus(AmmeterConstant.NOTACTIVATE);
        ammeter1.setBalance(0.00);
        return ammeterService.updateById(ammeter1) ? success() : fail("未知异常");
    }

    @RequestMapping("notkeep")
    @ResponseBody
    public ResultDto notkeep(Ammeter ammeter) {
        Ammeter ammeter1 = ammeterService.getById(ammeter.getAmmeterId());
        if (ammeter1 == null) {
            return fail("该电表不存在，请扫描正确的二维码");
        }
        if (!userService.getById(ammeter1.getUserId()).getAdminId().equals(ammeter1.getManagerId())) {
            return fail("您没有绑定此电表");
        }
        if (ammeter1.getStatus().equals(AmmeterConstant.ACTIVATE)) {
            return fail("该电表已激活");
        }
        ammeter1.setStatus(AmmeterConstant.ACTIVATE);
        return ammeterService.updateById(ammeter1) ? success() : fail();
    }

    @RequestMapping("valve")
    @ResponseBody
    public ResultDto valve(Ammeter ammeter) {
        Ammeter ammeter1 = ammeterService.getById(ammeter.getAmmeterId());
        if (ammeter1 == null) {
            return fail("该电表不存在，请扫描正确的二维码");
        }
        if (!userService.getById(ammeter.getUserId()).getAdminId().equals(ammeter1.getManagerId())) {
            return fail("您没有绑定此电表");
        }

        return success(ammeter1.getValve());
    }

    @RequestMapping("on")
    @ResponseBody
    public ResultDto on(String ammeterId) {
        Ammeter ammeter = ammeterService.getById(ammeterId);
        ammeter.setValve(AmmeterConstant.switchStatus.YES);
        return ammeterService.updateById(ammeter) ? success() : fail();
    }

    @RequestMapping("off")
    @ResponseBody
    public ResultDto off(String ammeterId) {
        Ammeter ammeter = ammeterService.getById(ammeterId);
        ammeter.setValve(AmmeterConstant.switchStatus.NO);
        return ammeterService.updateById(ammeter) ? success() : fail();
    }

    @RequestMapping("notification")
    @ResponseBody
    public ResultDto notification(String userId) {
        LambdaQueryWrapper<WarnAmmeterView> lambda = new QueryWrapper<WarnAmmeterView>().lambda();
        lambda.eq(WarnAmmeterView::getManagerId, userService.getById(userId).getAdminId());
        List<WarnAmmeterView> list = warnAmmeterViewService.list(lambda);
        return list.size() > 0 ? success(list) : fail();
    }

    @RequestMapping("paylog")
    @ResponseBody
    public ResultDto paylog(String userId) {
        LambdaQueryWrapper<payView> lambda = new QueryWrapper<payView>().lambda();
        lambda.eq(payView::getManagerId, userService.getById(userId).getAdminId());
        List<payView> list = payViewService.list(lambda);
        return list.size() > 0 ? success(list) : fail("暂无数据");
    }

    @RequestMapping("ammeterDetail")
    @ResponseBody
    public ResultDto ammeterDetail(String ammeterId) {
        Ammeter ammeter = ammeterService.getById(ammeterId);
        return success(ammeter);
    }

    @RequestMapping("/guestRecharge")
    @ResponseBody
    public ResultDto recharge(String choiceDate, String userId, MyPage<TenantPay> page) {
        User user = userService.getById(userId);
        List<TenantPay> tenantPays = tenantPayService.getGuestRecharge(choiceDate, user.getAdminId(), page);
        Double sum = 0.0;
        Double managerSum = 0.0;
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(choiceDate)) {
            map.put("time", choiceDate);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            map.put("time", sdf.format(new Date()));
        }
        List<TenantPay> sumPay = tenantPayService.getSumPay(choiceDate, user.getAdminId());
        for (TenantPay b : sumPay) {
            if (Objects.isNull(b)) {
                continue;
            }

            sum += b.getPayTrueAmouont();
            managerSum += b.getManagerAmount();
        }
        BigDecimal bigDecimal = new BigDecimal(sum);
        Double s = Double.parseDouble(bigDecimal.setScale(2, RoundingMode.HALF_UP).toString());
        BigDecimal bigDecimal1 = new BigDecimal(managerSum);
        Double s1 = Double.parseDouble(bigDecimal1.setScale(2, RoundingMode.HALF_UP).toString());
        map.put("sum", s);
        map.put("managerSum", s1);
        map.put("list", tenantPays);
        return success(map);
    }

    @RequestMapping("checkCode")
    @ResponseBody
    public ResultDto checkCode(String phone, Integer type, HttpServletRequest request) {
        if (type == 1) {
            Admin admin = adminService.getAdmin(phone);
            if (admin != null) {
                return fail("该手机号已绑定其他账户。");
            }
        }
        String s = MessageUtil.sendShortMessage(phone, SmsTemplateEnum.VERIFICATION_CODE.getCode());
        HttpSession session = request.getSession();
        session.setAttribute(phone, s);
        System.out.println(session);
        return success();
    }

    @RequestMapping("notactivate")
    @ResponseBody
    public ResultDto notactivate(Ammeter ammeter) {
        ammeter.setStatus(AmmeterConstant.NOTACTIVATE);
        return ammeterService.updateById(ammeter) ? success() : fail();
    }

    @RequestMapping("register")
    @ResponseBody
    public ResultDto register(Admin admin, String code, HttpServletRequest request,String openId) {
        if (StringUtils.isBlank(admin)) {
            return fail();
        }
        HttpSession session = request.getSession();
        String attribute = (String) session.getAttribute(admin.getMobilephone());
        if ((!attribute.equals(code))&&StringUtils.isBlank(attribute)) {
            return fail("验证码错误");
        }
        admin.setAdminId(GenerateIdUtils.get32Varchar());
        admin.setPassword(MD5Utils.string2MD5(admin.getPassword()));
        Date date = new Date();
        admin.setCreateTime(date)
                .setModifyTime(date)
                .setAccountNumber(admin.getMobilephone())
                .setAdminStatus(AdminConstant.position.LANDLORD)
                .setIsChange(0)
                .setValid(AdminConstant.VALID);
        List<String> list = new ArrayList<>();
        list.add("004");
        list.add("004-001");
        list.add("004-002");
        list.add("004-003");
        list.add("004-004");
        for (int i = 0;i<list.size();i++) {
            AdminRes adminRes = new AdminRes();
            adminRes.setAdminId(admin.getAdminId());
            adminRes.setResourceId(list.get(i));
            adminResService.save(adminRes);
        }
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getOpenId,openId);
        User user = userService.getOne(lambda);
        user.setAdminId(admin.getAdminId());
        user.setType(1);
        userService.updateById(user);
        boolean save = adminService.save(admin);
        return save ? success() : fail();
    }

    @RequestMapping("edit")
    @ResponseBody
    public ResultDto edit(String phone, String password, String code, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String attribute = (String) session.getAttribute(phone);
        if ((!attribute.equals(code))&&StringUtils.isBlank(attribute)) {
            return fail("验证码错误");
        }
        session.removeAttribute(phone);
        if (StringUtils.isBlank(phone, password)) {
            return fail();
        }
        Admin admin = adminService.getAdmin(phone);
        if (admin != null) {
            admin.setPassword(MD5Utils.string2MD5(password))
                    .setModifyTime(new Date());
            boolean save = adminService.updateById(admin);
            return save ? success() : fail();
        } else {
            return fail("该手机暂未注册。");
        }
    }

    //房东小程序批量修改电价
    @RequestMapping("editPrice")
    @ResponseBody
    public ResultDto editPrice(String ammeterIds,double dayPrice,double nightPrice,Date effectTime){
        String[] split = ammeterIds.split(",");
        List<Ammeter> list = new ArrayList<>();
        for(String ammeterId : split) {
            Ammeter ammeter = ammeterService.getById(ammeterId);
            ammeter.setDayPrice(dayPrice);
            ammeter.setNightPrice(nightPrice);
            ammeter.setEffectTime(effectTime);
            list.add(ammeter);
        }
        ammeterService.updateBatchById(list);
        return success();
    }

    //房东小程序批量修改服务费承担方
    @RequestMapping("editReat")
    @ResponseBody
    public ResultDto editReat(String ammeterIds,String assume){
        String[] split = ammeterIds.split(",");
        for(String ammeterId : split) {
            Ammeter ammeter = ammeterService.getById(ammeterId);
            if (Objects.isNull(ammeter)) {
                continue;
            }

            if (assume.equals("1")){
                ammeter.setIsSkimp(AmmeterConstant.IsSkimp.YES);
            }else if (assume.equals("0")){
                ammeter.setIsSkimp(AmmeterConstant.IsSkimp.NO);
            }
            ammeterService.updateById(ammeter);
        }
        return success();
    }
    @RequestMapping("/build/code")
    @ResponseBody
    public String buildQrCode(String ammeterId, String text) throws Exception {
//        BufferedImage qrCode = QrCodeUtils.getQRCode(qrData, text);
        String url = "https://bluetooth.zoercn.com/bluetooth/assets/";
        byte[] qrCodeBytes = CodeUtils.getQRCodeBytes(url + org.apache.commons.codec.binary.Base64.encodeBase64String(ammeterId.getBytes()), ammeterId);
//        String s = qrCode.toString();
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(qrCodeBytes).trim();
        return encode.replaceAll("\r","").replaceAll("\n","");
    }
}
